<?php 

namespace App\Utils;
use App\Exceptions\SendPhoneCodeException;
use GuzzleHttp\Client;
use Session;
use Config;

class PhoneMessage
{       

	private $mobile = '';

	private $tplId = '';

	private $tplValue = '';


	public function __construct($mobile, $tplId, $tplValue){
		$this->mobile = $mobile;

		$this->tplId = $tplId;

		$this->tplValue = $tplValue;
	}

    /**
     * 发送短信
     * @Author   leikes
     * @datetime 2016-03-31T10:29:26+0800
     * @param    [type]                   $mobile   需要发送的电话号码
     * @param    [type]                   $tplId    模板id,从配置中获取
     * @param    [type]                   $tplValue 传递模板里面的值,格式为：#code#=value
     * @return   [type]                             [description]
     */
    public function sendPhoneMsg()
    {   
       	$sendUrl = Config::get('global.phoneMsg.sendUrl'); //短信接口的URL

		$smsConf = [
			'key'   => Config::get('global.phoneMsg.key'), //您申请的APPKEY
		    'mobile'    => $this->mobile, //接受短信的用户手机号码
		    'tpl_id'    => $this->tplId, //您申请的短信模板ID，根据实际情况修改
		    'tpl_value' => '#code#='.$this->tplValue //您设置的模板变量，根据实际情况修改
		];


		$content = $this->juhecurl($sendUrl,$smsConf,'POST'); //请求发送短信


		if($content){
		    $result = json_decode($content,true);
		    $error_code = $result['error_code'];
		    if($error_code != 0){

		        $msg = $result['reason'];
		        
		        throw new SendPhoneCodeException($msg,$error_code);
		    }

		}else{
		    //返回内容异常，以下可根据业务逻辑自行修改
		    throw new SendPhoneCodeException();
		}
    }

    protected function juhecurl($url, $params=[],$httpMethod)
    {   
        $client = new Client(['base_uri'=>$url]);
        $response = $client->request($httpMethod, $url, ['form_params' => $params]);
        return $response->getBody()->getContents();
    }

 }
?>